package com.uu.safeguard.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.uu.safeguard.common.Constant;
import com.uu.safeguard.shirotoken.JwtToken;
import com.uu.safeguard.utils.HttpContextUtil;
import com.uu.safeguard.utils.JwtUtil;
import com.uu.safeguard.utils.TokenUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.jboss.logging.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Shiro自定义auth过滤器
 * @author cmt
 */
@Component
public class JwtFilter extends AuthenticatingFilter {
    private static Logger logger = Logger.getLogger(JwtFilter.class);
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 生成自定义token
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token
        String token = TokenUtil.getRequestToken((HttpServletRequest) request);
        return new JwtToken(token);
    }

    /**
     * 步骤1.所有请求全部拒绝访问
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @SneakyThrows
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        logger.info(JwtUtil.sign("210476686654", Constant.TOKEN_SECRET));
        logger.info("请求的url："+((HttpServletRequest) request).getServletPath());
        if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        return false;
    }

    /**
     * 步骤2，拒绝访问的请求，会调用onAccessDenied方法，onAccessDenied方法先获取 token，再调用executeLogin方法
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求token，如果token不存在，直接返回
        String token = TokenUtil.getRequestToken((HttpServletRequest) request);
        if (StringUtils.isBlank(token)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
            httpResponse.setCharacterEncoding("UTF-8");
            Map<String, Object> result = new HashMap<>();
            result.put("code", 1002);
            result.put("message", "请先登录");
            String json = MAPPER.writeValueAsString(result);
            httpResponse.getWriter().print(json);
            return false;
        }
        return executeLogin(request, response);
    }
    /**
     * @Description: Filter登录
     * @Param: [request, response]
     **/
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        JwtToken token = new JwtToken(httpServletRequest.getHeader("token"));
        if (token == null) {
            String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken must be created in order to execute a login attempt.";
            throw new IllegalStateException(msg);
        } else {
            try {
                Subject subject = this.getSubject(request, response);
                subject.login(token);
                return super.onLoginSuccess(token, subject, request, response);
            }catch (LockedAccountException var5) {
                request.setAttribute("code",1003);
                request.setAttribute("msg","运营商账户已冻结，请联系管理员");
                return this.onLoginFailure(token, var5, request, response);
            }
            catch (DisabledAccountException var5) {
                request.setAttribute("code",1005);
                request.setAttribute("msg","账户等级过低，请联系管理员");
                return this.onLoginFailure(token, var5, request, response);
            }
            catch (UnknownAccountException var5) {
                request.setAttribute("code",1004);
                request.setAttribute("msg","非本平台账户或无权限，请联系管理员");
                return this.onLoginFailure(token, var5, request, response);
            }
            catch (ExcessiveAttemptsException var5) {
                request.setAttribute("code",1006);
                request.setAttribute("msg","运营商账号未审核，请联系管理员");
                return this.onLoginFailure(token, var5, request, response);
            }
            catch (AuthenticationException var5) {
                request.setAttribute("code",1001);
                request.setAttribute("msg","登录凭证已失效，请重新登录");
                return this.onLoginFailure(token, var5, request, response);
            }
        }
    }

    /**
     * token失效时候调用
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtil.getOrigin());
        httpResponse.setCharacterEncoding("UTF-8");
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            Map<String, Object> result = new HashMap<>();
/*            result.put("code", 1001);
            result.put("message", "登录凭证已失效，请重新登录");*/
            result.put("code", request.getAttribute("code"));
            result.put("message", request.getAttribute("msg"));
            String json = MAPPER.writeValueAsString(result);
            httpResponse.getWriter().print(json);
        } catch (IOException e1) {
        }
        return false;
    }
    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

}